package main

import (
	"bufio"
	"bytes"
	"fmt"
	//	"io"
	"os/exec"
)

func main() {
	cmd1 := exec.Command("ps", "aux")
	cmd2 := exec.Command("grep", "apipe")

	stdout1, err := cmd1.StdoutPipe()
	if err != nil {
		fmt.Printf("Error : Can't obtain the stdout pipe for command :%s\n", err)
		return
	}
	if err := cmd1.Start(); err != nil {
		fmt.Printf("Error :The command No.1 can't be  startup %s\n", err)
		return
	}

	outputBuf1 := bufio.NewReader(stdout1)
	stdin2, err := cmd2.StdinPipe()
	if err != nil {
		fmt.Printf("Error : Cant not obtain the stdin pipe for command :%s\n", err)
		return
	}
	outputBuf1.WriteTo(stdin2)
	/*
	   method one :

	   	stdout2, err := cmd2.StdoutPipe()
	   	if err != nil {
	   		fmt.Printf("Error :Can not obtain the stdout pipe for command 2 :%s\n", err)
	   		return
	   	}
	   	outputBuf2 := bufio.NewReader(stdout2)

	   	if err := cmd2.Start(); err != nil {
	   		fmt.Printf("Error: The command can not be startup")
	   	}
	   	err = stdin2.Close()
	   	if err != nil {
	   		fmt.Printf("Error :Can not close the stdio pipe :%s\n", err)
	   		return
	   	}
	   	for {
	   		ouput, _, err := outputBuf2.ReadLine()
	   		if err != nil {
	   			if err == io.EOF {
	   				break
	   			}
	   			fmt.Printf("Error : Can't read date from buffer :%s\n", err)
	   			return
	   		}
	   		fmt.Printf("%s\n", string(ouput))
	   	}
	*/

	// method two
	var outputBuf2 bytes.Buffer
	cmd2.Stdout = &outputBuf2

	if err := cmd2.Start(); err != nil {
		fmt.Printf("Errror : The command  can not be startup %s\n", err)
		return
	}
	err = stdin2.Close()
	if err != nil {
		fmt.Printf("Error :Can not close the stdio pipe :%s\n", err)
		return
	}

	if err := cmd2.Wait(); err != nil {
		fmt.Printf("Error : Can not wait for the command :%s\n", err)
		return
	}
	fmt.Printf("%s", outputBuf2.String())
}
